const { Controller } = require('egg');

class BaseController extends Controller {
  success(data) {
    this.ctx.body = {
      code: 0,
      data,
    };
  }
  error(err) {
    this.ctx.body = {
      code: 1,
      err,
    };
  }
  async index() {
    const { ctx, service } = this;
    // 查询参数
    const { pageNum, pageSize, ...where } = ctx.query;
    const list = await service[this.entity].list(isNaN(pageNum) ? 1 : parseInt(pageNum), isNaN(pageNum) ? 1 : parseInt(pageSize), where);
    console.log(list);
    this.success(list);
  }
  async create() {
    const { ctx, service } = this;
    const entity = ctx.request.body;
    const res = await service[this.entity].create(entity);
    res ? this.success('创建成功') : this.error('创建失败');
  }
  async update() {
    const { ctx, service } = this;
    const entity = ctx.request.body;
    entity.id = ctx.params.id;
    const res = await service[this.entity].update(entity);
    res ? this.success('更新成功') : this.error('更新失败');
  }
  async destroy() {
    const { ctx, service } = this;
    const entityId = ctx.params.id;
    const res = await service[this.entity].delete(entityId);
    res ? this.success('删除成功') : this.error('删除失败');
  }
}

module.exports = BaseController;
